from os.path import join, expanduser, isdir, isfile
from os import makedirs
from ConfigParser import RawConfigParser
from resource_packer import unpack

class AlEarthConfig(RawConfigParser):
    defaultDir = join(expanduser("~"),".al_earth")
    defaultConfig = """\
[server]
homedir = %s
port = 8000
"""
    def __init__(self,iniPath=None):
        self.iniPath = iniPath
        if not self.iniPath:
            self.iniPath=join(self.defaultDir,"al_earth.conf")
        if not isfile(self.iniPath):
            if not isdir(self.defaultDir):
                makedirs(self.defaultDir)
            f=open(self.iniPath,"w")
            f.write(self.defaultConfig % self.defaultDir)
            f.close()
        RawConfigParser.__init__(self)
        self.read([self.iniPath])
        self.make_dirs()

    def make_dirs(self):
        homedir = self.get("server","homedir")
        tempdir = join(homedir,"templates")
        tempcache = join(homedir,"temp_cache")
        staticdir = join(homedir,"static")
        if not isdir(tempcache):
            makedirs(tempcache)
        if not isdir(tempdir):
            makedirs(tempdir)
            unpack(tempdir,"templates_res")
        if not isdir(staticdir):
            makedirs(staticdir)
            unpack(staticdir,"static_res")

    def set(self,section,key,value):
        RawConfigParser.set(self,section,key,value)
        f = open(self.iniPath,"w")
        self.write(f)
        f.close()
        self.read([self.iniPath])


if __name__=="__main__" :

    pass
